package com.javaai.project.tool;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.javaai.project.entity.Homedoctor;
import com.javaai.project.service.HomedoctorService;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class DoctorAssistantTools {
    @Autowired
    private HomedoctorService homedoctorService;
    
    @Tool(name = "预约挂号",value = "根据参数，需要先执行查询queryAppointment()方法，查询是否可预约，" +
            "并直接给用户回答是否可预约，" +
            "并让用户确认所有预约信息，用户确认后再进行预约。如果用户没有提供具体的医生姓名，请从向量存储中找到一位医生。")
    public String appointment(Homedoctor homedoctor) {
        log.info("===============>预约挂号:{}",homedoctor);
        // 查询数据库
        // 修改为使用QueryWrapper来构造查询条件
        QueryWrapper<Homedoctor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", homedoctor.getUsername())
                   .eq("id_card", homedoctor.getIdCard())
                   .eq("department", homedoctor.getDepartment())
                   .eq("date", homedoctor.getDate())
                   .eq("time", homedoctor.getTime());
                   
        if (homedoctor.getDoctorName() != null && !homedoctor.getDoctorName().isEmpty()) {
            queryWrapper.eq("doctor_name", homedoctor.getDoctorName());
        }
        
        Homedoctor homedoctordb = homedoctorService.getOne(queryWrapper);
        
        if (homedoctordb == null) {
            homedoctor.setId(null);
            boolean flag = homedoctorService.save(homedoctor);
            if (flag) {
                return "预约挂号成功，返回预约详情";
            } else {
                return "预约挂号失败，请重新预约";
            }
        }
        return "您在相同的科室与时间已经预约了，预约失败！";
    }
    
    @Tool(name = "查询是否已经预约挂号",value = "根据姓名、身份证号、科室、日期、时段、医生查询，返回结果true表示已经预约挂号了，不能再预约！")
    public boolean queryAppointment(
            @P(value = "姓名") String username,
            @P(value = "身份证号") String idCard,
            @P(value = "科室") String department,
            @P(value = "日期") String date,
            @P(value = "时间") String time,
            @P(value = "医生") String doctorName) {
        log.info("===============>查询是否已经预约挂号:{}");
        // 修改为使用QueryWrapper来构造查询条件
        QueryWrapper<Homedoctor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username)
                   .eq("id_card", idCard)
                   .eq("department", department)
                   .eq("date", date)
                   .eq("time", time);
                   
        if (doctorName != null && !doctorName.isEmpty()) {
            queryWrapper.eq("doctor_name", doctorName);
        }
        
        Homedoctor hd = homedoctorService.getOne(queryWrapper);
        return hd != null;
    }
}